package com.lk.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lk.common.ErrorCode;
import com.lk.config.RedisTemplateConfig;
import com.lk.constant.UserConstant;
import com.lk.exception.BusinessException;
import com.lk.mapper.UserMapper;
import com.lk.model.domain.User;
import com.lk.model.request.UserQueryRequest;
import com.lk.model.request.UserUpdatePassword;
import com.lk.service.UserService;
import com.lk.utils.AlgorithmUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.lk.constant.SystemConstant.PAGE_SIZE;
import static com.lk.constant.UserConstant.USER_LOGIN_STATE;
import static com.lk.utils.StringUtils.stringJsonListToLongSet;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private UserMapper userMapper;

    private RedisTemplateConfig redisTemplate;

    @Autowired
    private RedisTemplate<String, Object> Template;

    @Resource
    private StringRedisTemplate strRedisTemplate;
    @Autowired
    public UserServiceImpl(RedisTemplateConfig redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    //加盐，混淆密码
    private static final String SALT = "lk";


    /**
     * 注册
     *
     * @param userAccount 用户账户
     * @param userPassword  用户密码
     * @param checkPassword  二次确认密码
     * @return
     */
    @Override
    public long userRegister(String userName,String userAccount, String userPassword, String checkPassword) {

        //1.校验
        //判断是为空
        if (StringUtils.isAnyBlank(userName,userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数不能为空");
        }

        //用户名长度是否大于7
        if (userName.length()>7) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "昵称长度必须小于8");
        }

        //判断账号长度是否小于4
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号长度不能小于4位");
        }

        if (userAccount.length() > 16) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号长度不能大于16");
        }

        //判断两次密码是否相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码输入不一致");
        }

        //判断密码长度是否小于6
        if (userPassword.length() < 6 || checkPassword.length() < 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码至少6位");
        }

        //判断密码长度是否大于16
        if (userPassword.length() > 16 || checkPassword.length() > 16) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码最多16位");
        }

        //账号不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号含有特殊字符");
        }

        //判断账号不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        Long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.USER_ALREADY_EXIT,"用户名已经注册");
        }

        //2.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //头像路径

        //3.插入数据
        User user = new User();
        user.setUsername(userName);
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);

        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"注册失败");
        }

        return user.getId();
    }

    /**
     * 登录
     *
     * @param userAccount  用户账号
     * @param userPassword 用户密码
     * @param request
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验
        //判断是为空
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }

        //判断账号长度是否小于4
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号太短");
        }
        //判断密码长度是否小于8
        if (userPassword.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码太短");
        }

        //账号不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号含有特殊字符");
        }

        //2.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //查询账号密码是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);

        //用户不存在
        if (user == null) {
            log.info("login failed,userAccount cannot match userPassword");
            return null;
        }

        //3.用户信息脱敏
        User safetyUser = getSafetyUser(user);

        //4.记录用户的登录态
        String key= USER_LOGIN_STATE+ ":" + safetyUser.getId();
        strRedisTemplate.opsForValue().set(key, JSONArray.toJSONString(safetyUser));
        strRedisTemplate.expire(key, 24, TimeUnit.HOURS);

        return safetyUser;
    }


    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setProfile(originUser.getProfile());
        safetyUser.setTags(originUser.getTags());
        safetyUser.setUserIds(originUser.getUserIds());
        return safetyUser;
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        String key = USER_LOGIN_STATE + ":" + userId;
//        request.getSession().removeAttribute(USER_LOGIN_STATE);
        strRedisTemplate.delete(key);
        return true;
    }


    /**
     * 根据标签搜索用户（SQL 查询版）
     *
     * @param tagNameList 用户要拥有的标签
     * @return
     */
    @Deprecated
    private List<User> searchUsersByTagsBySQL(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 拼接 and 查询
        // like '%Java%' and like '%Python%'
        for (String tagName : tagNameList) {
            queryWrapper = queryWrapper.like("tags", tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }


    /**
     * 按标签搜索用户
     * 根据标签搜索用户（内存过滤）
     *
     * @param tagNameList 用户要拥有的标签
     * @param currentPage 当前页码
     * @return {@link Page}<{@link User}>
     */
    @Override
    public Page<User> searchUsersByTags(List<String> tagNameList, long currentPage) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        boolean isFirst = true; // 用于跟踪是否是第一个条件
        for (String tagName : tagNameList) {
            if (StringUtils.isNotEmpty(tagName)) {
                if (isFirst) {
                    userLambdaQueryWrapper.like(User::getTags, tagName); // 对于第一个条件，不需要or()
                    isFirst = false;
                } else {
                    userLambdaQueryWrapper.or().like(User::getTags, tagName); // 对于后续的条件，使用or().like()
                }
            }
        }
        return page(new Page<>(currentPage, PAGE_SIZE), userLambdaQueryWrapper);
    }


    /**
     * 更新用户信息
     *
     * @param user
     * @param loginUser
     * @return
     */
    @Override
    public int updateUser(User user, User loginUser) {
        //获取id
        long userId = user.getId();

        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 如果是管理员，允许更新任意用户;如果不是管理员，只允许更新当前（自己的）信息
        if (!isAdmin(loginUser) && userId != loginUser.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(userId);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.USER_NOT_EXIT);
        }
        //如果用户没有传任何要更新的值，就直接报错，不用执行 update 语句
        if(exceptIdOthersAllNull(user)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        //如果更新的是昵称userName
        if (user.getUsername() != null && user.getUsername().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"昵称不能为空");
        }

        //更新成功信息后清除推荐缓存
        String key = "CodePartner:user:recommend:"+userId;
        Template.delete(key);

        return userMapper.updateById(user);
    }

    /**
     * 获取当前登录用户信息
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        /*if (request == null) {
            return null;
        }
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return (User) userObj;*/

        if (request.getHeader("userId")==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        Long id = Long.valueOf(request.getHeader("userId"));


        String key= USER_LOGIN_STATE+ ":" + id;
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        String userStr = strRedisTemplate.opsForValue().get(key);
        User loginUser = JSONArray.parseObject(userStr, User.class);
//        User currentUser = (User) userObj;
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
//        Long id = loginUser.getId();
//        User user = userService.getById(id);

        User safetyUser = this.getSafetyUser(loginUser);

        return safetyUser;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        Long id = Long.valueOf(request.getHeader("userId"));
        String key = USER_LOGIN_STATE + ":" + id;
        String userStr = strRedisTemplate.opsForValue().get(key);
        User user = JSONArray.parseObject(userStr, User.class);
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }


    /**
     * 是否为管理员
     *
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser != null && loginUser.getUserRole() == UserConstant.ADMIN_ROLE;
    }


    /**
     * 判断一个User对象除了id其他属性是否全部为空
     *
     * @param user
     * @return
     */
    @Override
    public boolean exceptIdOthersAllNull(User user) {
        String username = user.getUsername();
        String userAccount = user.getUserAccount();
        String avatarUrl = user.getAvatarUrl();
        Integer gender = user.getGender();
        String profile = user.getProfile();
        String userPassword = user.getUserPassword();
        String phone = user.getPhone();
        String email = user.getEmail();
        Integer userStatus = user.getUserStatus();
        String tags = user.getTags();
        Date createTime = user.getCreateTime();
        Date updateTime = user.getUpdateTime();
        Integer userRole = user.getUserRole();
        Integer isDelete = user.getIsDelete();

        return (username==null&&userAccount==null&&avatarUrl==null
                &&gender==null&&profile==null&&userPassword==null
                &&phone==null&&email==null&&userStatus==null
                &&tags==null&&createTime==null&&updateTime==null
                &&userRole==null&&isDelete==null);
    }


    /**
     * 根据标签匹配与自己最相似的用户（心动模式）
     *
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {
        //查询所有tags不为null的用户的id和tags
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        //获取登陆者的标签列表，并转为字符串集合
        String myTags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> myTagList = gson.fromJson(myTags, new TypeToken<List<String>>() {
        }.getType());
        // 用户 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = "";
            if(user!=null){
            userTags = user.getTags();
            }

            // 无标签或者为当前用户自己时，跳过，继续下次循环
            if (StringUtils.isBlank(userTags) || Objects.equals(user.getId(), loginUser.getId())) {
                continue;
            }
            //获取本次循环中该用户的标签列表，并转为字符串集合
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            // 根据该用户标签和我的标签的最小距离，计算分数
            long distance = AlgorithmUtils.minDistance(myTagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本顺序的 userId 列表
        List<Long> userIdList = topUserPairList.stream()
                .map(pair -> pair.getKey().getId())
                .collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));

        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }


    @Override
    public void isLogin(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "请先登录");
        }
        Long id = Long.valueOf(request.getHeader("userId"));
        String key = USER_LOGIN_STATE + ":" + id;
        String userStr = strRedisTemplate.opsForValue().get(key);
        User currentUser = JSONArray.parseObject(userStr, User.class);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "请先登录");
        }
    }


    @Override
    public List<User> getFriendsById(User currentUser) {
        User loginUser = this.getById(currentUser.getId());
        Set<Long> friendsId = stringJsonListToLongSet(loginUser.getUserIds());
        return friendsId.stream().map(user -> this.getSafetyUser(this.getById(user))).collect(Collectors.toList());
    }

    @Override
    public boolean deleteFriend(User currentUser, Long id) {
        User loginUser = this.getById(currentUser.getId());
        User friendUser = this.getById(id);
        Set<Long> friendsId = stringJsonListToLongSet(loginUser.getUserIds());
        Set<Long> fid = stringJsonListToLongSet(friendUser.getUserIds());
        friendsId.remove(id);
        fid.remove(loginUser.getId());
        String friends = new Gson().toJson(friendsId);
        String fids = new Gson().toJson(fid);
        loginUser.setUserIds(friends);
        friendUser.setUserIds(fids);
        return this.updateById(loginUser) && this.updateById(friendUser);
    }

    @Override
    public List<User> userQuery(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        isLogin(request);
        String searchText = userQueryRequest.getSearchText();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.like(User::getUsername, searchText).or().like(User::getProfile, searchText);
        return this.list(userLambdaQueryWrapper);
    }

    @Override
    public List<User> searchFriend(UserQueryRequest userQueryRequest, User currentUser) {
        String searchText = userQueryRequest.getSearchText();
        User user = this.getById(currentUser.getId());
        Set<Long> friendsId = stringJsonListToLongSet(user.getUserIds());
        List<User> users = new ArrayList<>();
        Collections.shuffle(users);
        friendsId.forEach(id -> {
            User u = this.getById(id);
            if (u.getUsername().contains(searchText)) {
                users.add(u);
            }
        });
        return users;
    }

    /**
     * 收到用户标签
     *
     * @param id id
     * @return {@link List}<{@link String}>
     */
    @Override
    public List<String> getUserTags(Long id) {
        User user = this.getById(id);
        String userTags = user.getTags();
        Gson gson = new Gson();
        return gson.fromJson(userTags, new TypeToken<List<String>>() {
        }.getType());
    }

    /**
     * 更新标记
     *
     * @param tags   标签
     * @param userId 用户id
     */
    @Override
    public void updateTags(List<String> tags, Long userId) {
        User user = new User();
        Gson gson = new Gson();
        String tagsJson = gson.toJson(tags);
        user.setId(userId);
        user.setTags(tagsJson);
        this.updateById(user);
    }

    @Override
    public int updatePasswordById(UserUpdatePassword updatePassword, User currentUser) {
        long id = updatePassword.getId();
        String oldPassword = updatePassword.getOldPassword();
        String newPassword = updatePassword.getNewPassword();
        String checkPassword = updatePassword.getCheckPassword();
        if (StringUtils.isAnyBlank(oldPassword, newPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "输入有误");
        }
        // 密码就不小于8位吧
        if (oldPassword.length() < 8 || checkPassword.length() < 8 || newPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码小于6位");
        }
        // 密码和校验密码相同
        if (!newPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "输入密码不一致");
        }
        if (!isAdmin(currentUser) && currentUser.getId() != id) {
            throw new BusinessException(ErrorCode.NO_AUTH, "权限不足");
        }

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + oldPassword).getBytes(StandardCharsets.UTF_8));
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userAccount", currentUser.getUserAccount());
        userQueryWrapper.eq("userPassword", encryptPassword);
        User user = this.getOne(userQueryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed,userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }

        String newEncryptPassword = DigestUtils.md5DigestAsHex((SALT + newPassword).getBytes(StandardCharsets.UTF_8));

        currentUser.setUserPassword(newEncryptPassword);

        return userMapper.updateById(currentUser);
    }

    @Override
    public String redisFormat(Long key) {
        return String.format("CodePartner:user:search:%s", key);
    }


    @Override
    public List<User> random(long pageSize) {
        return userMapper.random(pageSize);
    }

    @Override
    public String getRealAvatarUrl(Long userId) {
        return userMapper.getRealAvatarUrl(userId);
    }

}




